package com.dave.admin.component.log;

import com.dave.admin.modular.boss.entity.WebLog;
import com.dave.admin.modular.boss.service.IWebLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author Dave
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LogListener {


    private final IWebLogService iWebLogService;

    /**
     * 使用这个需要注意的是 因为异步的 用户信息不会传播 会拿不到
     */
    @Async
    @Order
    @EventListener(LogEvent.class)
    public void saveLog(LogEvent event) {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(null, null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        WebLog webLog = (WebLog) event.getSource();
        iWebLogService.save(webLog);
    }
}
